﻿using System.Collections.Generic;
using UnityEngine;

namespace MFramework
{
    internal class GameObjectPoolCollection
    {
        public int Count
        {
            get => m_queue.Count;
        }

        /// <summary>
        /// 池对象生命周期，当池内对象超过此时间未被使用则自动释放
        /// </summary>
        public float PoolObjectLiftTime { get; set; }

        private Queue<PoolObjectInfo> m_queue = new Queue<PoolObjectInfo>();

        internal GameObject Dequeue()
        {
            return m_queue.Dequeue().target;
        }

        internal void Enqueue(GameObject target)
        {
            m_queue.Enqueue(new PoolObjectInfo() { target = target, enqueueTime = Time.realtimeSinceStartup });
        }

        internal void ReleaseExpiredObjects()
        {
            while(m_queue.Count > 0)
            {
                PoolObjectInfo info = m_queue.Peek();
                if (Time.realtimeSinceStartup - info.enqueueTime >= PoolObjectLiftTime)
                {
                    Object.Destroy(info.target);
                    m_queue.Dequeue();
                }
                else
                {
                    break;
                }
            }
        }

        internal struct PoolObjectInfo
        {
            internal GameObject target;
            /// <summary>
            /// 上此被回收进入队列的时间
            /// </summary>
            internal float enqueueTime;
        }
    }
}
